<template>
  <div class="app-container">
    <div v-if="showSearch" class="search-container">
      <CommonSearch
        :formConfig="searchColumns"
        :inline="true"
        labelWidth="78px"
        formItemWidth="auto"
        :model="searchParam"
      >
        <template #after>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <i-ep-refresh />
            重置
          </el-button>
        </template>
      </CommonSearch>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          @click="
            useDownload(
              '/mes/mesproducingstock/transferExport',
              '在制品',
              searchParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>
      <!-- 表格主体 -->
      <div v-show="showTable">
        <el-table
          ref="dataTableRef"
          v-loading="loading"
          v-bind="$attrs"
          :data="tableData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
          @sort-change="onTableSortChanged"
        >
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <!-- 表格内容操作 -->
          <template v-for="item in tableColumns" :key="item">
            <TableColumn v-if="item.prop && item.isShow" :column="item">
              <template v-for="slot in Object.keys($slots)" #[slot]="scope">
                <slot :name="slot" v-bind="scope"></slot>
              </template>
            </TableColumn>
          </template>
        </el-table>

        <el-pagination
          :background="true"
          :current-page="pageable.pageNum"
          :page-size="pageable.pageSize"
          :page-sizes="[10, 25, 50, 100]"
          :total="pageable.total"
          layout="total, sizes, prev, pager, next, jumper"
          class="mt-[20px]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 列设置 抽屉组件 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
      @col-handle="(e:boolean) => (showTable = e)"
    />
  </div>
</template>

<script setup lang="tsx">
import { useTable, useDictionary, useDownload } from "@/utils/useTable";
import { filterOrder } from "@/utils/commonHooks";
import {
  getPlantList,
  getWorkShopList,
  getMaterials,
} from "@/utils/commonData";
import { getMesprocessList } from "@/api/andon/andon";
import request from "@/utils/request";

defineOptions({
  name: "STATISTICALQUERYINPROGRESS",
  inheritAttrs: false,
});

/** 自定义设置方法   start **/

// 搜索参数 设置为响应式
const searchColumns: any = reactive([
  {
    type: "select",
    label: "工厂",
    isShow: true,
    fieldName: "plantId",
    placeholder: "请选择工厂",
    initValue: null,
    defaultFirstOption: true,
    optionList: [],
    change: (e) => {
      selectPlant(e);
    },
  },
  {
    type: "select",
    label: "工作中心",
    isShow: true,
    fieldName: "workCenterId",
    placeholder: "请选择工作中心",
    initValue: null,
    defaultFirstOption: true,
    optionList: [],
    change: (e) => {
      selectWorkCenter(e);
    },
  },

  {
    type: "input",
    label: "存货编码",
    isShow: true,
    fieldName: "materialCode",
    placeholder: "请选择存货编码",
    initValue: "",
  },
  {
    type: "input",
    label: "工序流转单",
    isShow: true,
    fieldName: "materialBarcode",
    placeholder: "请输入工序流转单",
    defaultFirstOption: true,
    initValue: "", // 默认值
  },
  {
    type: "input", // 普通输入框
    isShow: true,
    inputType: "text", // 类型, text/textarea
    label: "生产计划号", // 标签文本
    fieldName: "producePlanCode", // 字段名称
    placeholder: "请输入生产计划号", // 提示文字
    initValue: "", // 默认值
  },
  {
    type: "input", // 普通输入框
    isShow: true,
    inputType: "text", // 类型, text/textarea
    label: "加工单号", // 标签文本
    fieldName: "workOrderCode", // 字段名称
    placeholder: "请输入加工单号", // 提示文字
    initValue: "", // 默认值
  },
  {
    type: "input", // 普通输入框
    isShow: true,
    inputType: "text", // 类型, text/textarea
    label: "批次号", // 标签文本
    fieldName: "materialBatch", // 字段名称
    placeholder: "请输入批次号", // 提示文字
    initValue: "", // 默认值
  },
]);

// 接收 columns 并设置为响应式
const tableColumns = reactive([
  {
    prop: "plantCode",
    label: "工厂",
    isShow: true,
    width: 100,
    align: "left",
    render: (scope: any) => <span>{scope.row?.plantCode ?? ""}</span>,
  },
  {
    prop: "workCenterCode",
    label: "工作中心",
    isShow: true,
    minWidth: 180,
    align: "left",
    render: (scope: any) => (
      <span>{`${scope.row.workCenterCode ?? ""}-${
        scope.row.workCenterName ?? ""
      }`}</span>
    ),
  },
  {
    prop: "materialCode",
    label: "存货编码-名称",
    isShow: true,
    minWidth: 180,
    align: "left",
    render: (scope: any) => (
      <span>{`${scope.row.materialCode ?? ""}-${
        scope.row.materialName ?? ""
      }`}</span>
    ),
  },
  {
    prop: "materialBarcode",
    label: "工序流转单号",
    isShow: true,
    minWidth: 180,
    align: "left",
  },
  {
    prop: "producePlanCode",
    label: "生产计划号",
    isShow: true,
    minWidth: 180,
    align: "left",
  },
  {
    prop: "workOrderCode",
    label: "加工单号",
    isShow: true,
    minWidth: 180,
    align: "left",
  },
  {
    prop: "isValid",
    label: "是否合格",
    isShow: true,
    minWidth: 100,
    render: (scope: any) =>
      scope.row?.isValid == 1 ? (
        <el-tag class="text-[13px]">
          {useDictionary("YesNo", scope.row.isValid)}
        </el-tag>
      ) : (
        <el-tag type="warning" class="text-[13px]">
          {useDictionary("YesNo", scope.row.isValid)}
        </el-tag>
      ),
  },
  {
    prop: "materialBatch",
    label: "批次号",
    isShow: true,
    minWidth: 120,
    align: "left",
  },
  {
    prop: "materialQuantity",
    label: "数量",
    align: "right",
    isShow: true,
    headerAlign: "center",
    minWidth: 100,
  },
  {
    prop: "quantityUnit",
    label: "数量单位",
    isShow: true,
    minWidth: 100,
    align: "left",
    render: (scope: any) => (
      <span>{useDictionary("MeasurementUnit", scope.row.quantityUnit)}</span>
    ),
  },
]);

// 是否显示搜索框
const showSearch = ref(true);

// 是否table
const showTable = ref(true);

/** 列表项自定义方法   end **/

// 请求参数
const requestApi = "/mes/mesproducingstock/selectByPageTransfer";

// 是否需要分页
const pagination = true;

const initParam = reactive({ sort: {} });

// 初始化搜索参数数据
const searchParamInit = {};

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
// function dataCallBack() {}   //需要处理
const dataCallBack = ref(undefined); //无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError
);

// 如果初始化表格需要排序=》const initParam = reactive({sort:''});
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
onMounted(async () => {
  getTableList();
  getSelectPlantList();
});

// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}

// 获取工厂列表
async function getSelectPlantList() {
  const list = (await getPlantList()) ?? [];
  list?.map((item) => {
    item.label = `${item.organizationCode}`;
    item.value = `${item.id}`;
  });
  searchColumns[0].optionList = list;
  searchParam.value.plantId = list[0].id;
  selectPlant(searchParam.value.plantId);
}

// 工厂选择
async function selectPlant(e: string) {
  if (e) {
    // 获取工作中心列表
    const list = (await getWorkShopList(e)) ?? [];
    list?.map((item) => {
      item.label = `${item.workshopCode}-${item.workshopName}`;
      item.value = `${item.id}`;
    });
    searchColumns[1].optionList = list;
    searchParam.value.workCenterId = "";
    searchColumns[2].optionList = [];
    searchParam.value.materialId = "";
  } else {
    searchColumns[1].optionList = [];
    searchParam.value.workCenterId = "";
    searchColumns[2].optionList = [];
    searchParam.value.materialId = "";
  }
}

// 工作中心选择
function selectWorkCenter(e: any) {
  if (e) {
    searchColumns[2].optionList = [];
    searchParam.value.materialId = "";
    // getMaterialList();
  } else {
    searchColumns[2].optionList = [];
    searchParam.value.materialId = "";
  }
}

// 加工时间选择
function getRequestTime(data: any) {
  if (data) {
    searchParam.value.requestTimeStart = data[0];
    searchParam.value.requestTimeEnd = data[1];
  } else {
    searchParam.value.requestTimeStart = "";
    searchParam.value.requestTimeEnd = "";
  }
}

// 工序列表获取
async function getProcessList(id) {
  const { data } = await getMesprocessList({ workCenterId: id, enabled: 1 });
  data?.forEach((item) => {
    item.label = `${item.processCode}-${item.processName}`;
    item.value = `${item.id}`;
  });
  searchColumns[2].optionList = data;
}

// 物料列表获取
async function getMaterialList() {
  const list = await getMaterials(
    searchParam.value.plantId,
    searchParam.value.workCenterId
  );
  list?.forEach((item) => {
    item.label = `${item.materialCode}-${item.materialName}`;
    item.value = `${item.id}`;
  });
  searchColumns[2].optionList = list;
}

// 重置数据处理
function handleReset() {
  reset();
  getSelectPlantList();
  searchColumns[1].optionList = [];
  searchColumns[2].optionList = [];
}
</script>
